/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.nmpp.se.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import cn.ac.iie.di.ban.nmpp.commons.RuntimeEnv;
import cn.ac.iie.di.ban.nmpp.config.Configuration;
import cn.ac.iie.di.ban.nmpp.handler.TableSe2DWHandler;
import cn.ac.iie.di.ban.nmpp.metastore.TableSe2DBRule;
import java.io.File;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author ulss
 */
public class NEWMPP2MStartup {

    static Map<String, TableSe2DWHandler> tableHandlerSet = new HashMap<String, TableSe2DWHandler>();
    static volatile boolean stopped;

    private static org.apache.log4j.Logger logger = Logger.getLogger(NEWMPP2MStartup.class.getName());
    public static String confPath;

    public static void showUsage() {
        System.out.println("Usage:java -jar ");
    }

    public static void main(String[] args) {
        NEWMPP2MStartup.confPath = args[0];
//        NEWMPP2MStartup.confPath = "C:\\WchengxuMaven\\workgit\\ban-ycl-common-mpp\\src\\main\\resources";
        PropertyConfigurator.configure(NEWMPP2MStartup.confPath + File.separator + "log4j.properties");
        try {
            init();
            startup();
        } catch (Exception ex) {
            logger.error("starting newmpp is failed for " + ex.getMessage(), ex);
        }
        System.exit(0);
    }

    private static void startup() throws Exception {
        logger.info("checking newmpp rule in metastore....");
        Map<String, List> tableSe2DBRuleOPSet = RuntimeEnv.metaStoreManager.getTableSe2DBRuleSet();//castable
        List<TableSe2DBRule> newTableSe2DBRuleList = tableSe2DBRuleOPSet.get("new");
        if (newTableSe2DBRuleList.size() > 0) {
            logger.info("found " + newTableSe2DBRuleList.size() + " new newmpp rules");
            for (TableSe2DBRule tableSe2DBRule : newTableSe2DBRuleList) {
                TableSe2DWHandler tableHandler = TableSe2DWHandler.getTableSe2DBHandler(tableSe2DBRule);
                if (tableHandler == null) {
                    logger.error("init tableHandler for " + tableSe2DBRule.getRuleName() + " unsuccessfully");
                    RuntimeEnv.metaStoreManager.removeTableSe2DBRule(tableSe2DBRule);
                    continue;
                }
                RuntimeEnv.metaStoreManager.registerHandler(tableHandler);
                tableHandlerSet.put(tableSe2DBRule.getRuleName(), tableHandler);
            }
            TableSe2DWHandler.startupConsumer();
        } else {
            logger.info("no new newmpp rules was found");
        }

        while (true) {
            if (stopped) {
                logger.info("stop consumer...");
                TableSe2DWHandler.shutdownConsumer();
                for (String tableHandlerName : tableHandlerSet.keySet()) {
                    logger.info("stop handler " + tableHandlerName);
                    tableHandlerSet.get(tableHandlerName).stop();
                }
                logger.info("newmpp exit successfully");
                break;
            } else {
                try {
                    logger.info("waiting....");
                    Thread.sleep(10000);
                } catch (Exception ex) {
                }
            }
        }
    }

    private static void init() throws Exception {
        String configurationFileName = "ban-ycl-common-mpp.properties";
        logger.info("TheFullFileName is  " + NEWMPP2MStartup.confPath + File.separator + configurationFileName);
        Configuration conf = Configuration.getConfiguration(NEWMPP2MStartup.confPath + File.separator + configurationFileName);
        if (conf == null) {
            throw new Exception("reading " + configurationFileName + " is failed");
        }

        logger.info("initializng runtime enviroment...");
        if (!RuntimeEnv.initialize(conf)) {
            throw new Exception("initializng runtime enviroment is failed");
        }
        logger.info("register shutdown hook");
        KillHandler killHandler = new KillHandler();
        killHandler.registerSignal("TERM");
        logger.info("register shutdown hook successfully");
    }

    public static void stop() {
        stopped = true;
    }

    public static Map getTableHandlerSet() {
        return tableHandlerSet;
    }
}
